package com.lhc.service.impl;

import com.lhc.dao.OrderDoMapper;
import com.lhc.dao.SequenceDoMapper;
import com.lhc.dataObject.OrderDo;
import com.lhc.dataObject.SequenceDo;
import com.lhc.error.BusniessException;
import com.lhc.error.EmBussinessError;
import com.lhc.service.ItemService;
import com.lhc.service.OrderService;
import com.lhc.service.UserService;
import com.lhc.service.model.ItemModel;
import com.lhc.service.model.OrderModel;
import com.lhc.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sun.tools.jinfo.JInfo;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private UserService userService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private OrderDoMapper orderDoMapper;

    @Autowired
    private SequenceDoMapper sequenceDoMapper;


    @Override
    @Transactional
    public OrderModel createOrder(Integer userId, Integer itemId, Integer account) throws BusniessException {
        //校验下单状态 ，下单商品是否存在 用户是否合法， 购买数量是否合理
        ItemModel itemModel = itemService.getItemById(itemId);
        if (itemModel == null) {
            throw new BusniessException(EmBussinessError.PARAMETER_VALIDATION_ERROR, "商品不存在");
        }
        UserModel userModel = userService.selectByPrimaryKey(userId);
        if (userModel == null) {
            throw new BusniessException(EmBussinessError.PARAMETER_VALIDATION_ERROR, "用户不存在");
        }
        if (account <= 0 || account > 99) {
            throw new BusniessException(EmBussinessError.PARAMETER_VALIDATION_ERROR, "数量信息不正确");
        }
        //落单减库存
        boolean result = itemService.decreaseStock(itemId, account);
        if (!result) {
            throw new BusniessException(EmBussinessError.STOCK_NOT_ENOUGH);
        }
        //订单入库
        OrderModel orderModel = new OrderModel();
        orderModel.setAccount(account);
        orderModel.setItemId(itemId);
        orderModel.setUserId(userId);
        orderModel.setItemPrice(itemModel.getPrice());
        orderModel.setOrderPrice(itemModel.getPrice().multiply(new BigDecimal(account)));
        //生成流水号
        orderModel.setId(this.generateOrderNo());
        OrderDo orderDo = this.convertFromOderModel(orderModel);
        orderDoMapper.insertSelective(orderDo);
        return orderModel;
    }



    @Transactional(propagation = Propagation.REQUIRES_NEW)
    String generateOrderNo() {
        StringBuilder stringBuilder = new StringBuilder();
        String datetime = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE).replace("-", "");
        stringBuilder.append(datetime);

        SequenceDo sequenceDo = sequenceDoMapper.getSequenceByName("order_info");
        int sequence = 0;
        sequence = sequenceDo.getCurrentValue();
        sequenceDo.setCurrentValue(sequenceDo.getCurrentValue() + sequenceDo.getStep());
        sequenceDoMapper.updateByPrimaryKeySelective(sequenceDo);
        String sequenceStr = String.valueOf(sequence);
        for (int i = 1; i < 6 - sequenceStr.length(); i++) {
            stringBuilder.append(0);
        }
        stringBuilder.append(sequenceStr);
        //数据库分表分库 暂时写死
        stringBuilder.append("00");
        return stringBuilder.toString();
    }

    private OrderDo convertFromOderModel(OrderModel orderModel) {
        if (orderModel == null) {
            return null;
        }
        OrderDo orderDo = new OrderDo();
        BeanUtils.copyProperties(orderModel, orderDo);
        orderDo.setItemPrice(orderModel.getItemPrice().doubleValue());
        orderDo.setOrderPrice(orderModel.getOrderPrice().doubleValue());
        return orderDo;
    }
}
